#!/bin/bash
# repo_urls
# packages
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/debug.sh

init_env()
{
	yum install -y dnf-plugins-core
	touch .dockerignore
	echo '*' > .dockerignore
}

add_repos()
{
	export yum_conf="/tmp/repos.conf"
	rm -rf ${yum_conf} && touch ${yum_conf}

	i=0
	for repo_url in ${repo_urls[@]}
	do
		cat >> ${yum_conf} <<-EOF
		[${i}]
		name=${i}
		baseurl=${repo_url}
		enabled=1
		gpgcheck=0
		priority=${i}
		EOF
		let i=i+1
	done
}

down_load_packages()
{
	export packages_dir="/tmp/packages"
	rm -rf ${packages_dir} && mkdir ${packages_dir}
	cd ${packages_dir}
	for package in ${packages[@]}
	do
		yumdownloader ${package} --downloaddir=${packages_dir} -c ${yum_conf} || die "down load pacakge error: ${package}"
		cur_package=$(ls | grep *.rpm)
		rpm2cpio ${cur_package} | cpio -div
		rm -f ${cur_package}
	done

	export package_files=/tmp/package_files
	for f in $(ls)
	do
		strip_file ${f}
		echo "COPY $f /$f" >> ${package_files}
	done
}

strip_file()
{
	for ele in $(ls $1)
	do
		dof=$1/${ele}
		if [ -d $dof ]
		then
			strip_file ${dof}
		else
			strip -s ${dof}
		fi
	done
}

create_dockerfile()
{
	cd ${packages_dir}
	cat ${package_files}
	cat > Dockerfile <<-EOF
	FROM scratch
	$(cat ${package_files})
	EOF
}

docker_build()
{
	docker build -t ${pipeline_name}:latest .
	docker save -o ${pipeline_name}.tar ${pipeline_name}:latest
}

upload_image_tar()
{
	upload_one_curl ${pipeline_name}.tar ${upload_image_dir} || die "upload ${pipeline_name}.tar to ${upload_image_dir} error."
}

init_env
add_repos
down_load_packages
create_dockerfile
docker_build
upload_image_tar
